package com.uziot.bucket.security.service;

import com.uziot.bucket.security.config.LoginUser;
import com.uziot.bucket.security.dao.domain.SysUser;
import com.uziot.bucket.security.dao.mapper.SysMenuMapper;
import com.uziot.bucket.security.dao.mapper.SysUserMapper;
import com.uziot.bucket.security.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className UserDetailsServiceImpl
 * @date 2020-10-31 16:45:04
 * @description 用户验证处理
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectUserByUserName(username);
        // 此处并不建议直接抛出异常，建议将异常状态交给SpringSecurity处理，将用户的状态赋值给UserDetail即可
        if (StringUtils.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if ("2".equals(sysUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new UsernameNotFoundException("对不起，您的账号：" + username + " 已被删除");
        } else if ("1".equals(sysUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UsernameNotFoundException("对不起，您的账号：" + username + " 已停用");
        }
        return this.createLoginUser(sysUser);
    }

    /**
     * 创建登陆用户信息
     *
     * @param user 用户
     * @return 用户
     */
    public UserDetails createLoginUser(SysUser user) {
        // 装载用户资源权限信息
        List<String> perms = sysMenuMapper.selectMenuPermsByUserId(user.getUserId());
        return new LoginUser(user, new HashSet<>(perms));
    }
}
